﻿using System.Web.Mvc;
using EPiAbstractions;
using EPiAbstractions.Filters;
using EPiMVC.Controllers;
using EPiServer.Core;
using EPiServer.Security;
using Moq;
using Xunit;

namespace EPiMVC.Tests.EPiServerControllerBaseTests
{
    public class OnAuthorizationCalledAndAccessFilterReturns
    {
        [Fact]
        public void True_NoResultIsSetForAuthorizationContext()
        {
            Implementation controller = SetupController(true);
            AuthorizationContext authorizationContext = new AuthorizationContext();

            controller.CallOnAuthorization(authorizationContext);

            Assert.Null(authorizationContext.Result);
        }

        private Implementation SetupController(bool allowedAccess)
        {
            PageData currentPage = new PageData();
            Mock<IFilterAccessFacade> fakeFilterAccess = new Mock<IFilterAccessFacade>();
            fakeFilterAccess.Setup(filter => filter.QueryDistinctAccessEdit(currentPage, AccessLevel.Read)).Returns(allowedAccess);
            Implementation controller = new Implementation(null, null, fakeFilterAccess.Object);
            controller.CurrentPage = currentPage;
            return controller;
        }

        [Fact]
        public void False_ResultIsSetToHttpUnauthorizedResult()
        {
            Implementation controller = SetupController(false);
            AuthorizationContext authorizationContext = new AuthorizationContext();

            controller.CallOnAuthorization(authorizationContext);
            
            Assert.NotNull(authorizationContext.Result);
            Assert.IsType<HttpUnauthorizedResult>(authorizationContext.Result);
        }

        public class Implementation : EPiServerControllerBase<PageData>
        {
            public Implementation() {}

            public Implementation(IDataFactoryFacade dataFactory, IFilterForVisitorFacade filterForVisitor, IFilterAccessFacade filterAccess)
                : base(dataFactory, filterForVisitor, filterAccess) { }

            public void CallOnAuthorization(AuthorizationContext filterContext)
            {
                base.OnAuthorization(filterContext);
            }
        }
    }
}
